<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"><title>Java运行时数据区 | 江一行</title><meta name="author" content="江一行"><meta name="copyright" content="江一行"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="referrer" content="no-referrer"><meta name="description" content="组成JVM 主要由四大部分组成：ClassLoader（类加载器），Runtime Data Area（运行时数据区），Execution Engine（执行引擎），Native Interface（本地库接口），下图可以大致描述 JVM 的结构。   ClassLoader：负责加载字节码文件即 class 文件，class 文件在文件开头有特定的文件标示，并且 ClassLoader 只负责c">
<meta property="og:type" content="article">
<meta property="og:title" content="Java运行时数据区">
<meta property="og:url" content="https://j_yh.gitee.io/Java/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/index.html">
<meta property="og:site_name" content="江一行">
<meta property="og:description" content="组成JVM 主要由四大部分组成：ClassLoader（类加载器），Runtime Data Area（运行时数据区），Execution Engine（执行引擎），Native Interface（本地库接口），下图可以大致描述 JVM 的结构。   ClassLoader：负责加载字节码文件即 class 文件，class 文件在文件开头有特定的文件标示，并且 ClassLoader 只负责c">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://w.wallhaven.cc/full/j8/wallhaven-j8x7ym.jpg">
<meta property="article:published_time" content="2023-02-24T16:17:12.000Z">
<meta property="article:modified_time" content="2023-03-02T11:50:21.111Z">
<meta property="article:author" content="江一行">
<meta property="article:tag" content="面试">
<meta property="article:tag" content="JVM">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://w.wallhaven.cc/full/j8/wallhaven-j8x7ym.jpg"><link rel="shortcut icon" href="/img/favicon.ico"><link rel="canonical" href="https://j_yh.gitee.io/Java/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/index.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.css" media="print" onload="this.media='all'"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.min.css" media="print" onload="this.media='all'"><script>const GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  noticeOutdate: undefined,
  highlight: {"plugin":"highlighjs","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":200},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '天',
  date_suffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'fancybox',
  Snackbar: {"chs_to_cht":"你已切换为繁体","cht_to_chs":"你已切换为简体","day_to_night":"你已切换为深色模式","night_to_day":"你已切换为浅色模式","bgLight":"#49b1f5","bgDark":"#1f1f1f","position":"bottom-left"},
  source: {
    justifiedGallery: {
      js: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.js',
      css: 'https://cdn.jsdelivr.net/npm/flickr-justified-gallery/dist/fjGallery.min.css'
    }
  },
  isPhotoFigcaption: false,
  islazyload: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  }
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Java运行时数据区',
  isPost: true,
  isHome: false,
  isHighlightShrink: true,
  isToc: true,
  postUpdate: '2023-03-02 19:50:21'
}</script><noscript><style type="text/css">
  #nav {
    opacity: 1
  }
  .justified-gallery img {
    opacity: 1
  }

  #recent-posts time,
  #post-meta time {
    display: inline !important
  }
</style></noscript><script>(win=>{
    win.saveToLocal = {
      set: function setWithExpiry(key, value, ttl) {
        if (ttl === 0) return
        const now = new Date()
        const expiryDay = ttl * 86400000
        const item = {
          value: value,
          expiry: now.getTime() + expiryDay,
        }
        localStorage.setItem(key, JSON.stringify(item))
      },

      get: function getWithExpiry(key) {
        const itemStr = localStorage.getItem(key)

        if (!itemStr) {
          return undefined
        }
        const item = JSON.parse(itemStr)
        const now = new Date()

        if (now.getTime() > item.expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return item.value
      }
    }
  
    win.getScript = url => new Promise((resolve, reject) => {
      const script = document.createElement('script')
      script.src = url
      script.async = true
      script.onerror = reject
      script.onload = script.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        script.onload = script.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(script)
    })
  
    win.getCSS = (url,id = false) => new Promise((resolve, reject) => {
      const link = document.createElement('link')
      link.rel = 'stylesheet'
      link.href = url
      if (id) link.id = id
      link.onerror = reject
      link.onload = link.onreadystatechange = function() {
        const loadState = this.readyState
        if (loadState && loadState !== 'loaded' && loadState !== 'complete') return
        link.onload = link.onreadystatechange = null
        resolve()
      }
      document.head.appendChild(link)
    })
  
      win.activateDarkMode = function () {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      win.activateLightMode = function () {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }
      const t = saveToLocal.get('theme')
    
          if (t === 'dark') activateDarkMode()
          else if (t === 'light') activateLightMode()
        
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        if (asideStatus === 'hide') {
          document.documentElement.classList.add('hide-aside')
        } else {
          document.documentElement.classList.remove('hide-aside')
        }
      }
    
    const detectApple = () => {
      if(/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)){
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
    })(window)</script><meta name="generator" content="Hexo 6.3.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img is-center"><img src="/img/avatar.png" onerror="onerror=null;src='/img/friend_404.gif'" alt="avatar"/></div><div class="sidebar-site-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">7</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">5</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div><hr/><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header" style="background-image: url('https://w.wallhaven.cc/full/j8/wallhaven-j8x7ym.jpg')"><nav id="nav"><span id="blog-info"><a href="/" title="江一行"><span class="site-name">江一行</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 首页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/link/"><i class="fa-fw fas fa-link"></i><span> 友链</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于</span></a></div></div><div id="toggle-menu"><a class="site-page" href="javascript:void(0);"><i class="fas fa-bars fa-fw"></i></a></div></div></nav><div id="post-info"><h1 class="post-title">Java运行时数据区</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2023-02-24T16:17:12.000Z" title="发表于 2023-02-25 00:17:12">2023-02-25</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2023-03-02T11:50:21.111Z" title="更新于 2023-03-02 19:50:21">2023-03-02</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Java/">Java</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-wordcount"><i class="far fa-file-word fa-fw post-meta-icon"></i><span class="post-meta-label">字数总计:</span><span class="word-count">2.4k</span><span class="post-meta-separator">|</span><i class="far fa-clock fa-fw post-meta-icon"></i><span class="post-meta-label">阅读时长:</span><span>7分钟</span></span><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title="Java运行时数据区"><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">阅读量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span><span class="post-meta-separator">|</span><span class="post-meta-commentcount"><i class="far fa-comments fa-fw post-meta-icon"></i><span class="post-meta-label">评论数:</span><a href="/Java/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/#post-comment" itemprop="discussionUrl"><span class="valine-comment-count" data-xid="/Java/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/" itemprop="commentCount"><i class="fa-solid fa-spinner fa-spin"></i></span></a></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="post-content" id="article-container"><h2 id="组成"><a href="#组成" class="headerlink" title="组成"></a>组成</h2><p>JVM 主要由四大部分组成：ClassLoader（类加载器），Runtime Data Area（运行时数据区），Execution Engine（执行引擎），Native Interface（本地库接口），下图可以大致描述 JVM 的结构。</p>
<p><img src="https://gitee.com/j_yh/typroa/raw/master/images/image-20230225001207134.png" alt="image-20230225001207134"></p>
<ul>
<li>ClassLoader：负责加载字节码文件即 class 文件，class 文件在文件开头有特定的文件标示，并且 ClassLoader 只负责class 文件的加载，至于它是否可以运行，则由 Execution Engine 决定。</li>
<li>Runtime Data Area：是存放数据的，分为五部分：Stack（虚拟机栈），Heap（堆），Method Area（方法区），PC Register（程序计数器），Native Method Stack（本地方法栈）。几乎所有的关于 Java 内存方面的问题，都是集中在这块。</li>
<li>Execution Engine：执行引擎，也叫 Interpreter。Class 文件被加载后，会把指令和数据信息放入内存中，Execution Engine 则负责把这些命令解释给操作系统，即将 JVM 指令集翻译为操作系统指令集。</li>
<li>Native Interface：负责调用本地接口的。作用是调用不同语言的接口给 JAVA 用，会在 Native Method Stack 中记录对应的本地方法，然后调用该方法时就通过 Execution Engine 加载对应的本地 lib。</li>
</ul>
<h2 id="程序计数器"><a href="#程序计数器" class="headerlink" title="程序计数器"></a>程序计数器</h2><p>Java 虚拟机的多线程是由线程轮流切换，分配处理器的执行时间的方法来实现的。任一确定时刻，一个处理器只会执行一个线程中的指令。为了线程切换后恢复到正确的执行位置，每个线程需要各自独立的程序计数器（Program Counter Register）。</p>
<p>程序计数器是一块比较小的内存空间，可以视作当前线程所执行的字节码的行号指示器。字节码解释器改变程序计数器的值来选取下一个需要执行的指令。字节码解释器对字节码进行解释后变为机器码交给 cpu 处理。</p>
<p>特点</p>
<blockquote>
<ol>
<li>程序计数器是线程私有的一块内存区域</li>
<li>这块区域不存在内存溢出</li>
</ol>
</blockquote>
<h2 id="Java虚拟机栈"><a href="#Java虚拟机栈" class="headerlink" title="Java虚拟机栈"></a>Java虚拟机栈</h2><p>Java 虚拟机栈（Java Virtual Machine Stack）是描述 Java 方法执行的线程内存模型：每个方法被执行时，Java 虚拟机就会同步创建一个栈帧（Stack Frame）用于存储局部变量表、操作数栈、动态连接、方法出口等信息。从每个方法被调用到执行完毕，都对应一个栈帧从入栈到出栈的过程。</p>
<p><code>局部变量表</code>中存放编译期可知的基本数据类型和对象引用类型，局部变量表所需空间在编译期间完成分配。</p>
<h3 id="分配栈内存"><a href="#分配栈内存" class="headerlink" title="分配栈内存"></a>分配栈内存</h3><figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">-Xss size </span><br><span class="line">-Xss1m</span><br><span class="line">-Xss1024k</span><br></pre></td></tr></table></figure>

<h3 id="思考"><a href="#思考" class="headerlink" title="思考"></a>思考</h3><p>方法内局部变量是否线程安全？</p>
<blockquote>
<ul>
<li>方法内局部变量没有逃离方法的作用范围，则线程安全</li>
<li>如果局部变量引用了对象，并且逃离方法的作用范围，需要考虑线程安全</li>
</ul>
</blockquote>
<p>垃圾回收机制涉及栈内存吗？</p>
<blockquote>
<p>不涉及</p>
</blockquote>
<p>栈内存分配越大越好吗？</p>
<blockquote>
<p>栈内存分配越大，执行速度越慢（可能），递归层次越深，线程个数越少。</p>
</blockquote>
<h3 id="特点"><a href="#特点" class="headerlink" title="特点"></a>特点</h3><blockquote>
<ol>
<li>线程私有的，且生命周期与线程相同。</li>
<li>每个线程运行时需要的内存，成为虚拟机栈</li>
<li>每个栈由多个方法组成，对应每次方法调用时占用的内存</li>
<li>每个线程只能有一个活动栈帧，对应正在执行的方法</li>
</ol>
</blockquote>
<h2 id="本地方法栈"><a href="#本地方法栈" class="headerlink" title="本地方法栈"></a>本地方法栈</h2><p>为虚拟机使用使用到本地（native）方法服务。</p>
<h2 id="堆"><a href="#堆" class="headerlink" title="堆"></a>堆</h2><p>Java 堆（Java Heap），是虚拟机所管理的最大的一块内存区域，所有线程共享此区域，只能存放对象的实例。垃圾收集器管理的内存区域就是堆。因为有栈上分配、标量替换，所有 java 对象实例都存储在堆中的说法不够严谨。</p>
<p>分配堆内存</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">-Xmx size</span><br><span class="line">-Xms size</span><br></pre></td></tr></table></figure>

<p>特点</p>
<blockquote>
<p>线程共享，需要考虑线程安全问题</p>
<p>有垃圾回收机制</p>
</blockquote>
<h2 id="方法区"><a href="#方法区" class="headerlink" title="方法区"></a>方法区</h2><p>方法区（Method Area）同 Java 堆一样，各个线程共享的内存区域，用于存储被虚拟机加载的类型信息、常量、静态变量、即时编译器编译后的代码缓存。<strong>方法区是堆的一个逻辑部分</strong>，但是要二者要区分开来。</p>
<h3 id="关于永久代与元空间"><a href="#关于永久代与元空间" class="headerlink" title="关于永久代与元空间"></a>关于永久代与元空间</h3><p>在JDK8以前，许多人愿意把方法区称作永生代，实际并不等价，只是使用永生代来实现方法区，使得垃圾收集器能够管理这部分内存。</p>
<p>永生代分配内存</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">-XX:MaxPermSize=8m</span><br></pre></td></tr></table></figure>

<p>JDK8中，完全废弃永生代的概念，采用在本地内存中实现的元空间（Meta Space）代替，将永生代中的字符串常量池、静态变量、类型信息等放入元空间</p>
<p>元空间分配内存</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">-XX:MaxMetaspaceSize=8m</span><br></pre></td></tr></table></figure>

<h3 id="运行时常量池"><a href="#运行时常量池" class="headerlink" title="运行时常量池"></a>运行时常量池</h3><p>运行时常量池（Runtime Constant Pool）是方法区的一部分。Class 文件中有类的模板、字段、方法、接口等描述信息外，还有常量池表，用于存放编译期生成的各种字面量和符号引用，这部分内容会在类加载后存放到运行时常量池。</p>
<p>运行时常量池会将符号引用翻译为直接引用后存储，具有动态性，运行期间可以将新的常量放入池中，如 String 类的 intern() 方法。</p>
<p>归纳</p>
<blockquote>
<p>常量池就是一张表，虚拟机指令根据常量池表找到要执行的类名、方法名、参数类型、字面量等信息，是 *.class 文件中的。在类被加载时，它的常量池信息就会放入运行时常量池，并将符号地址转换为真实地址。</p>
</blockquote>
<h3 id="StringTable特性"><a href="#StringTable特性" class="headerlink" title="StringTable特性"></a>StringTable特性</h3><p>字符串常量池，1.8在堆中，1.6在永久代中。本质是hash表。</p>
<ul>
<li>常量池中的字符串只是符号，第一次用的时候才变为对象</li>
<li>串池的缓存机制，避免了重复创建字符串对象</li>
<li>字符串变量拼接原理：new StringBuffer</li>
<li>字符串常量与常量拼接：编译期优化</li>
<li>使用 intern() 方法主动将串池中没有的字符串对象加入到串池<ul>
<li>1.8尝试将字符串放入串池时，有则直接返回串池中的地址，没有，则会返回串池中创建的这个对象地址</li>
<li>1.6尝试将字符串放入串池时，有则直接返回串池中的地址，没有复制一份再放（放的副本的地址），会返回串池中创建的这个对象（副本）地址</li>
</ul>
</li>
</ul>
<figure class="highlight java"><table><tr><td class="code"><pre><span class="line">String s1=<span class="string">&quot;a&quot;</span>;<span class="comment">//字符串字面量创建</span></span><br><span class="line">String s2=<span class="string">&quot;b&quot;</span>;</span><br><span class="line">String s3=<span class="string">&quot;ab&quot;</span>;<span class="comment">//s123属于常量池中的信息，它们会被加载到运行时常量池，此时还是符号。ldc #2（字节码执行时）会把符号变为字符串对象</span></span><br><span class="line">String s4=s1+s2;<span class="comment">//==&gt; new StringBuffer.append(&quot;a&quot;).append(&quot;b&quot;).toString(),  toString()又相当于new String(&quot;ab&quot;)</span></span><br><span class="line">System.out.println(s4==s3);<span class="comment">//false，s4 new 出来的，</span></span><br><span class="line">String s5=<span class="string">&quot;a&quot;</span>+<span class="string">&quot;b&quot;</span>;<span class="comment">//javac 在编译期间会进行优化，结果在编译期确定为&quot;ab&quot;</span></span><br><span class="line">System.out.println(s5==s3);<span class="comment">//true</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>字符串字面量创建会放入串池。</p>
<p>new 创建字符串，会在堆中创建一个新的字符串对象，并且不会检查是否串池中是否存在。</p>
<p>&#x3D;&#x3D; 判断二者的地址是否一样</p>
</blockquote>
<h3 id="StringTable调优"><a href="#StringTable调优" class="headerlink" title="StringTable调优"></a>StringTable调优</h3><p>堆内存分配500Mb，方法区开启打印StringTable统计信息，方法区中StringTable桶个数设置为1009（最小值）</p>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line">-Xms500m -Xmx500m -XX:+PrintStringTableStatistics -XX:StringTableSize=1009</span><br></pre></td></tr></table></figure>

<p>思路</p>
<blockquote>
<p>调整 -XX:StringTableSize&#x3D;桶个数</p>
<p>考虑将字符串对象入池 intern()</p>
</blockquote>
<h2 id="直接内存"><a href="#直接内存" class="headerlink" title="直接内存"></a>直接内存</h2><p>直接内存（Direct Memory）不是虚拟机的运行时数据区的一部分，也不是《Java虚拟机规范》定义的内存区域。JDK1.4中新加入了 NIO（New Input&#x2F;Output）类，它可以使用 Native 函数库直接分配堆外内存，然后通过一个存储在 Java 堆中的 DirectByteBuffer 对象作为这块内存的引用进行操作。能够避免在 Java 堆和 Native 堆中来回复制数据。</p>
<ul>
<li>常用于 NIO ，数据缓冲区</li>
<li>分配回收成本高，读写性能高</li>
<li>不受 JVM 内存回收管理</li>
</ul>
<h3 id="分配与回收"><a href="#分配与回收" class="headerlink" title="分配与回收"></a>分配与回收</h3><ul>
<li>使用 Unsafe 对象完成直接内存的分配与回收，回收需要主动调用 freeMemory() 方法</li>
<li>DirectByteBuffer 的实现类内部，使用了 Cleaner（虚引用）来监测 DirectByteBuffer 对象，一旦 DirectByteBuffer 对象被垃圾回收了，那么 ReferenceHandler 线程就会通过 Cleaner 中的 clean 方法调用 freeMemory() 来释放直接内存。</li>
</ul>
<h3 id="禁用显示垃圾回收"><a href="#禁用显示垃圾回收" class="headerlink" title="禁用显示垃圾回收"></a>禁用显示垃圾回收</h3><blockquote>
<p>禁用原因：显示垃圾回收就是代码中的 System.gc() ， 是 Full gc 会影响性能。</p>
<p>注意：如果开启禁用显示垃圾回收，需要考虑手动使用 unsafe 方法回收直接内存</p>
</blockquote>
<figure class="highlight bash"><table><tr><td class="code"><pre><span class="line"><span class="comment">#使代码中 System.gc() 无效</span></span><br><span class="line">-XX:+DisableExplicitGC</span><br></pre></td></tr></table></figure>

<h2 id="个人总结"><a href="#个人总结" class="headerlink" title="个人总结"></a>个人总结</h2><p>关于Java 虚拟机的学习，本人在 B 站上跟着 <a target="_blank" rel="noopener" href="https://www.bilibili.com/video/BV1yE411Z7AP/?spm_id_from=333.337.search-card.all.click">黑马程序员</a> 的视频课顺序，并结合《深入理解Java虚拟机》做笔记。</p>
<p>程序计数器、虚拟机栈、本地方法栈 3 个区域与线程生命周期共存亡，栈中的栈帧分配多少空间在类结构确定时就已知（编译器会优化），这几个区域的内存分配与回收具有确定性。关于堆和方法区就有明显的不确定性，这部分内存的分配与回收具有动态性。</p>
<hr>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="https://j_yh.gitee.io/">江一行</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="https://j_yh.gitee.io/Java/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/">https://j_yh.gitee.io/Java/Java%E5%86%85%E5%AD%98%E5%8C%BA%E5%9F%9F/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="https://j_yh.gitee.io" target="_blank">江一行</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/%E9%9D%A2%E8%AF%95/">面试</a><a class="post-meta__tags" href="/tags/JVM/">JVM</a></div><div class="post_share"><div class="social-share" data-image="https://w.wallhaven.cc/full/j8/wallhaven-j8x7ym.jpg" data-sites="wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"><div class="prev-post pull-left"><a href="/%E6%95%B0%E6%8D%AE%E5%BA%93/redis%E5%9F%BA%E7%A1%80/" title="redis基础"><img class="cover" src="/img/my/363b122c528f54df4a0446b6bab05515.png" onerror="onerror=null;src='/img/404.png'" alt="cover of previous post"><div class="pagination-info"><div class="label">上一篇</div><div class="prev_info">redis基础</div></div></a></div><div class="next-post pull-right"><a href="/Java/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/" title="垃圾回收"><img class="cover" src="https://w.wallhaven.cc/full/n6/wallhaven-n6plgx.jpg" onerror="onerror=null;src='/img/404.png'" alt="cover of next post"><div class="pagination-info"><div class="label">下一篇</div><div class="next_info">垃圾回收</div></div></a></div></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><div><a href="/Java/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/" title="垃圾回收"><img class="cover" src="https://w.wallhaven.cc/full/n6/wallhaven-n6plgx.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-25</div><div class="title">垃圾回收</div></div></a></div><div><a href="/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6/" title="类加载机制"><img class="cover" src="/img/my/archive.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-03-04</div><div class="title">类加载机制</div></div></a></div><div><a href="/Java/Java%E5%9F%BA%E7%A1%80/" title="Java 基础"><img class="cover" src="https://w.wallhaven.cc/full/4o/wallhaven-4oovr5.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-27</div><div class="title">Java 基础</div></div></a></div><div><a href="/Java/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="多线程"><img class="cover" src="/img/my/2510c39011c5be704182423e3a695e91.png" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-28</div><div class="title">多线程</div></div></a></div><div><a href="/Java/%E9%9B%86%E5%90%88/" title="集合"><img class="cover" src="https://w.wallhaven.cc/full/lm/wallhaven-lmwg12.jpg" alt="cover"><div class="content is-center"><div class="date"><i class="far fa-calendar-alt fa-fw"></i> 2023-02-28</div><div class="title">集合</div></div></a></div></div></div><hr/><div id="post-comment"><div class="comment-head"><div class="comment-headline"><i class="fas fa-comments fa-fw"></i><span> 评论</span></div></div><div class="comment-wrap"><div><div class="vcomment" id="vcomment"></div></div></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info"><div class="is-center"><div class="avatar-img"><img src="/img/avatar.png" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info__name">江一行</div><div class="author-info__description">花有重开日，人无再少年</div></div><div class="card-info-data site-data is-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">7</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">5</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">2</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/Jjiangyuhang"><i class="fab fa-github"></i><span>关注我</span></a><div class="card-info-social-icons is-center"><a class="social-icon" href="https://github.com/Jjiangyuhang" target="_blank" title="Github"><i class="fab fa-github"></i></a><a class="social-icon" href="/jiang.yu.hang@qq.com" target="_blank" title="Email"><i class="fas fa-envelope"></i></a><a class="social-icon" href="https://space.bilibili.com/434232050" target="_blank" title="BiliBili"><i class="fa-brands fa-bilibili"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">一些学习笔记，欢迎交流讨论。</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%BB%84%E6%88%90"><span class="toc-number">1.</span> <span class="toc-text">组成</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%A8%8B%E5%BA%8F%E8%AE%A1%E6%95%B0%E5%99%A8"><span class="toc-number">2.</span> <span class="toc-text">程序计数器</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#Java%E8%99%9A%E6%8B%9F%E6%9C%BA%E6%A0%88"><span class="toc-number">3.</span> <span class="toc-text">Java虚拟机栈</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E9%85%8D%E6%A0%88%E5%86%85%E5%AD%98"><span class="toc-number">3.1.</span> <span class="toc-text">分配栈内存</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E6%80%9D%E8%80%83"><span class="toc-number">3.2.</span> <span class="toc-text">思考</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%89%B9%E7%82%B9"><span class="toc-number">3.3.</span> <span class="toc-text">特点</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%9C%AC%E5%9C%B0%E6%96%B9%E6%B3%95%E6%A0%88"><span class="toc-number">4.</span> <span class="toc-text">本地方法栈</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%A0%86"><span class="toc-number">5.</span> <span class="toc-text">堆</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E6%96%B9%E6%B3%95%E5%8C%BA"><span class="toc-number">6.</span> <span class="toc-text">方法区</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%85%B3%E4%BA%8E%E6%B0%B8%E4%B9%85%E4%BB%A3%E4%B8%8E%E5%85%83%E7%A9%BA%E9%97%B4"><span class="toc-number">6.1.</span> <span class="toc-text">关于永久代与元空间</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E8%BF%90%E8%A1%8C%E6%97%B6%E5%B8%B8%E9%87%8F%E6%B1%A0"><span class="toc-number">6.2.</span> <span class="toc-text">运行时常量池</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#StringTable%E7%89%B9%E6%80%A7"><span class="toc-number">6.3.</span> <span class="toc-text">StringTable特性</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#StringTable%E8%B0%83%E4%BC%98"><span class="toc-number">6.4.</span> <span class="toc-text">StringTable调优</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%9B%B4%E6%8E%A5%E5%86%85%E5%AD%98"><span class="toc-number">7.</span> <span class="toc-text">直接内存</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#%E5%88%86%E9%85%8D%E4%B8%8E%E5%9B%9E%E6%94%B6"><span class="toc-number">7.1.</span> <span class="toc-text">分配与回收</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#%E7%A6%81%E7%94%A8%E6%98%BE%E7%A4%BA%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6"><span class="toc-number">7.2.</span> <span class="toc-text">禁用显示垃圾回收</span></a></li></ol></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%B8%AA%E4%BA%BA%E6%80%BB%E7%BB%93"><span class="toc-number">8.</span> <span class="toc-text">个人总结</span></a></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item"><a class="thumbnail" href="/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6/" title="类加载机制"><img src="/img/my/archive.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="类加载机制"/></a><div class="content"><a class="title" href="/Java/%E7%B1%BB%E5%8A%A0%E8%BD%BD%E6%9C%BA%E5%88%B6/" title="类加载机制">类加载机制</a><time datetime="2023-03-04T02:35:24.000Z" title="发表于 2023-03-04 10:35:24">2023-03-04</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/Java/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="多线程"><img src="/img/my/2510c39011c5be704182423e3a695e91.png" onerror="this.onerror=null;this.src='/img/404.png'" alt="多线程"/></a><div class="content"><a class="title" href="/Java/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" title="多线程">多线程</a><time datetime="2023-02-28T12:55:06.000Z" title="发表于 2023-02-28 20:55:06">2023-02-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/Java/%E9%9B%86%E5%90%88/" title="集合"><img src="https://w.wallhaven.cc/full/lm/wallhaven-lmwg12.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="集合"/></a><div class="content"><a class="title" href="/Java/%E9%9B%86%E5%90%88/" title="集合">集合</a><time datetime="2023-02-27T16:22:33.000Z" title="发表于 2023-02-28 00:22:33">2023-02-28</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/Java/Java%E5%9F%BA%E7%A1%80/" title="Java 基础"><img src="https://w.wallhaven.cc/full/4o/wallhaven-4oovr5.png" onerror="this.onerror=null;this.src='/img/404.png'" alt="Java 基础"/></a><div class="content"><a class="title" href="/Java/Java%E5%9F%BA%E7%A1%80/" title="Java 基础">Java 基础</a><time datetime="2023-02-27T13:30:00.000Z" title="发表于 2023-02-27 21:30:00">2023-02-27</time></div></div><div class="aside-list-item"><a class="thumbnail" href="/Java/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/" title="垃圾回收"><img src="https://w.wallhaven.cc/full/n6/wallhaven-n6plgx.jpg" onerror="this.onerror=null;this.src='/img/404.png'" alt="垃圾回收"/></a><div class="content"><a class="title" href="/Java/%E5%9E%83%E5%9C%BE%E5%9B%9E%E6%94%B6/" title="垃圾回收">垃圾回收</a><time datetime="2023-02-25T03:02:39.000Z" title="发表于 2023-02-25 11:02:39">2023-02-25</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2023 By 江一行</div><div class="framework-info"><span>框架 </span><a target="_blank" rel="noopener" href="https://hexo.io">Hexo</a><span class="footer-separator">|</span><span>主题 </span><a target="_blank" rel="noopener" href="https://github.com/jerryc127/hexo-theme-butterfly">Butterfly</a></div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="浅色和深色模式转换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside_config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><a id="to_comment" href="#post-comment" title="直达评论"><i class="fas fa-comments"></i></a><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/ui/dist/fancybox.umd.min.js"></script><script src="https://cdn.jsdelivr.net/npm/node-snackbar/dist/snackbar.min.js"></script><script>function panguFn () {
  if (typeof pangu === 'object') pangu.autoSpacingPage()
  else {
    getScript('https://cdn.jsdelivr.net/npm/pangu/dist/browser/pangu.min.js')
      .then(() => {
        pangu.autoSpacingPage()
      })
  }
}

function panguInit () {
  if (false){
    GLOBAL_CONFIG_SITE.isPost && panguFn()
  } else {
    panguFn()
  }
}

document.addEventListener('DOMContentLoaded', panguInit)</script><div class="js-pjax"><script>function loadValine () {
  function initValine () {
    const valine = new Valine(Object.assign({
      el: '#vcomment',
      appId: 'vnyeujKjy6AaK5O0RLSaVwC9-gzGzoHsz',
      appKey: 'P0RFxhK58YSXPxBnDRAbZgYd',
      avatar: 'monsterid',
      serverURLs: '',
      emojiMaps: "",
      path: window.location.pathname,
      visitor: false
    }, null))
  }

  if (typeof Valine === 'function') initValine() 
  else getScript('https://cdn.jsdelivr.net/npm/valine/dist/Valine.min.js').then(initValine)
}

if ('Valine' === 'Valine' || !false) {
  if (false) btf.loadComment(document.getElementById('vcomment'),loadValine)
  else setTimeout(loadValine, 0)
} else {
  function loadOtherComment () {
    loadValine()
  }
}</script></div><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/dist/activate-power-mode.min.js"></script><script>POWERMODE.colorful = true;
POWERMODE.shake = true;
POWERMODE.mobile = false;
document.body.addEventListener('input', POWERMODE);
</script><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>